//
//  DoctorDetailController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/26.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
/// 医生主页
class DoctorDetailController: BaseViewController {
    
    private var viewModel: DoctorDetailViewModel? {
        didSet {
            tableView.isHidden = false
            headerView.configure(with: viewModel)
            setOrderBtn()
            setTableFooterView()
            tableView.reloadData()
        }
    }
    
    private let doctorId: String
    
    init(with doctorId: String) {
        self.doctorId = doctorId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .background
            appearance.shadowColor = .clear
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
        }else{
            navigationController?.navigationBar.setBackgroundImage(UIImage(color: .background), for: .default)
            
        }
       
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        setNavWhite()
    }
    
    private lazy var headerView = UINib.loadViewFrom(DoctorDetailHeaderView.self)

    @IBOutlet weak var orderBtn: UIButton! 
    
    @IBOutlet weak var orderBtnView: UIView! {
        didSet {
            orderBtnView.backgroundColor = .background
            orderBtnView.isHidden = true
        }
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.rowHeight = 80
            tableView.estimatedRowHeight = UITableView.automaticDimension
            if #available(iOS 15.0, *) {
                tableView.sectionHeaderTopPadding = 0
            }
            tableView.backgroundColor = .background
            tableView.register(DoctorDetailCell.nibForCell(), forCellReuseIdentifier: DoctorDetailCell.reuseIdentifier())
            tableView.register(DoctorDetailSelectCell.nibForCell(), forCellReuseIdentifier: DoctorDetailSelectCell.reuseIdentifier())
            
            tableView.register(DoctorDetailMemoCell.nibForCell(), forCellReuseIdentifier: DoctorDetailMemoCell.reuseIdentifier())
            tableView.register(DoctorDetailInfoCell.nibForCell(), forCellReuseIdentifier: DoctorDetailInfoCell.reuseIdentifier())
            tableView.register(DoctorDetailSectionHeader.nibForCell(), forHeaderFooterViewReuseIdentifier: DoctorDetailSectionHeader.reuseIdentifier())
            tableView.register(DoctorDetailTeamCell.nibForCell(), forCellReuseIdentifier: DoctorDetailTeamCell.reuseIdentifier())
            tableView.register(DoctorDetailregistrationCell.nibForCell(), forCellReuseIdentifier: DoctorDetailregistrationCell.reuseIdentifier())
            tableView.register(DoctorDetailCloudCell.nibForCell(), forCellReuseIdentifier: DoctorDetailCloudCell.reuseIdentifier())
        }
    }
    
    @IBOutlet private weak var activityView: UIActivityIndicatorView!
   
    private func setTableFooterView() {
        var viewHeight: CGFloat = 0.0
        if viewModel?.selectType == .registration {
            viewHeight = 12.0
        } else {
            viewHeight = 73.0
        }
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: viewHeight))
        tableView.tableFooterView = view
    }
    
    private func setOrderBtn() {
        orderBtnView.isHidden = viewModel?.selectType == .registration
        orderBtn.setTitle(viewModel?.buttonStr, for: .normal)
    }
    
    private func setupUI() {
        tableView.tableHeaderView = headerView
        headerView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.size.equalTo(CGSize(width: screenW, height: 120))
        }
    }
    
    private func loadData() {
        activityView.startAnimating()
        DoctorDetailViewModel.getDoctorDetail(doctorId: doctorId, success: { model in
            self.activityView.stopAnimating()
            self.viewModel = DoctorDetailViewModel(model: model)
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
}

extension DoctorDetailController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        if section == 1 {
            if let vm = viewModel {
                if vm.doctorTeamListDto.count > 0 {
                    return 1
                } else {
                    return 0
                }
            }
        }
        if section == 2 {
            return 2
        }
        if section == 3 {
            switch viewModel?.selectType {
            case .registration:
                return viewModel?.numberOfRowsForGeneral ?? 0
            case .advisory:
                return 0
            case .cloud:
                return viewModel?.numberOfRows ?? 0
            default:
                return 0
            }
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailInfoCell.reuseIdentifier(),
                                                     for: indexPath) as! DoctorDetailInfoCell
            cell.delegate = self
            if let vm = viewModel {
                cell.updateData(vm: vm)
            }
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailTeamCell.reuseIdentifier(),
                                                     for: indexPath) as! DoctorDetailTeamCell
            if let vm = viewModel {
                cell.updateData(vm: vm)
                cell.delegate = self
            }
            return cell
        }
        if indexPath.section == 2 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailSelectCell.reuseIdentifier(),
                                                         for: indexPath) as! DoctorDetailSelectCell
                cell.delegate = self
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailMemoCell.reuseIdentifier(),
                                                         for: indexPath) as! DoctorDetailMemoCell
                if let type = viewModel?.selectType {
                    cell.updateData(type: type)
                }
                return cell
            }
        }
        if indexPath.section == 3 {
            if viewModel?.selectType == .registration {
                let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailregistrationCell.reuseIdentifier(), for: indexPath) as! DoctorDetailregistrationCell
                if let vm = viewModel?.generalViewModel(for: indexPath) {
                    cell.updateData(vm: vm, indexPath: indexPath)
                    cell.delegate = self
                }
                return cell
            } else if viewModel?.selectType == .advisory {
                let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailCloudCell.reuseIdentifier(), for: indexPath)
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: DoctorDetailCell.reuseIdentifier(),
                                                         for: indexPath) as! DoctorDetailCell
                if let vm = viewModel?.viewModel(for: indexPath) {
                    cell.configure(with: vm)
                }
                cell.delegate = self
                return cell
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 || section == 2 {
            let headerView = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: 54))
            let titleLabel = UILabel(frame: CGRect(x: 16, y: 0, width: screenW - 32, height: 54))
            titleLabel.centerY = headerView.centerY
            titleLabel.font = UIFont.medium(16)
            titleLabel.textColor = UIColor.textDark
            headerView.addSubview(titleLabel)
            switch section {
            case 1:
                titleLabel.text = "我的团队"
                headerView.backgroundColor = UIColor.background
            case 2:
                titleLabel.text = "医生服务"
                headerView.backgroundColor = UIColor.white
            default:
                titleLabel.text = ""
                headerView.backgroundColor = UIColor.clear
            }
            return headerView
        }
        if section == 3 {
            if viewModel?.selectType == .advisory {
                return UIView()
            }
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: DoctorDetailSectionHeader.reuseIdentifier()) as? DoctorDetailSectionHeader
            header?.clickedClosure = { [weak self] in
                guard let self = self else { return }
                let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                if self.viewModel?.selectType == .registration {
                    agreementView.show(type: .registrationRule)
                } else {
                    agreementView.show(type: .reservationRule)
                }
            }
            return header
        }
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }
        if section == 1 {
            if let vm = viewModel {
                if vm.doctorTeamListDto.count > 0 {
                    return 54
                } else {
                    return 0
                }
            }
            return 0
        }
        return 54
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 1 {
            return 16
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 130
        }
        if indexPath.section == 3 {
            return 80
        }
        return UITableView.automaticDimension
    }
}

extension DoctorDetailController: DoctorDetailInfoCellDelegate {
    func DoctorDetailInfoCellAction(btn: UIButton) {
        self.tableView.reloadData()
    }
}

extension DoctorDetailController: DoctorDetailTeamCellDelagate {
    func doctorDetailTeamCellDidSelectItem(indexPath: IndexPath) {
        if let vm = viewModel {
            let vm = vm.teamViewModel(for: indexPath)
            let vc = ESGTeamInquiryDetailController(teamId: vm.id)
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension DoctorDetailController: DoctorDetailSelectCellDelegate {
    func doctorDetailSelectCell(actionBtn: UIButton) {
        viewModel?.selectType = DoctorSelectType(rawValue: actionBtn.tag - 10) ?? DoctorSelectType.advisory
    }
}

extension DoctorDetailController: DoctorDetailregistrationCellDelegate{
    func doctorDetailregistrationCellBtnAction(indexPath: IndexPath) {
        if let vm = viewModel?.generalViewModel(for: indexPath), let doctorVm = viewModel {
            let pick = UINib.loadViewFrom(DoctorDetailRegistrationView.self)
            pick.frame = CGRect(x: 0, y: 0, width: screenW, height: screenH)
            pick.updateData(scheduleVm: vm, doctorVm: doctorVm)
            pick.delegate = self
            pick.show()
        }
    }
}

extension DoctorDetailController: DoctorDetailRegistrationViewDelagate {
    func doctorDetailRegistrationViewDidSelectedRow(indexPath: IndexPath, scheduleVm: DoctorScheduleViewModel, registrationListVm: CloudReserveDateListViewModel) {
        if let vm = viewModel {

            self.pushRegistrationConfirmController(doctorVm: vm, scheduleVm: scheduleVm, registrationListVm: registrationListVm)
        }
    }
    
    private func pushRegistrationConfirmController(doctorVm: DoctorDetailViewModel,
                                                   scheduleVm: DoctorScheduleViewModel,
                                                   registrationListVm: CloudReserveDateListViewModel) {
        let vc = RegistrationConfirmController(with: doctorVm, scheduleVm: scheduleVm, registrationListVm: registrationListVm)
        navigationController?.pushViewController(vc, animated: true)
    }

}

extension DoctorDetailController: DoctorDetailCellDelegate {
    func didClickedReserveDoctor(_ cell: DoctorDetailCell) {
        guard let indexPath = tableView.indexPath(for: cell), let vm = viewModel else { return }
        pushReserveInfoVc(with: vm, indexPath: indexPath)
    }
    
    private func pushReserveInfoVc(with vm: DoctorDetailViewModel, indexPath: IndexPath) {
//        let newCloudVc = NewCloudReserveController(with: vm, rowVm: vm.viewModel(for: indexPath))
//        navigationController?.pushViewController(newCloudVc, animated: true)
    }
}

extension DoctorDetailController {
    
    @IBAction func orderBtnAction(_ sender: Any) {
        if viewModel?.selectType == .advisory {
            reserveAdvisory()
        } else {
            reserveCloud()
        }
    }
    
    private func reserveAdvisory() {
        guard let vm = viewModel else { return }

        switch vm.doctorType {
        case .advisory, .all:
            let adMedicalRecordsVC = AdMedicalRecordsController()
            adMedicalRecordsVC.doctorVm = vm
            navigationController?.pushViewController(adMedicalRecordsVC, animated: true)
        default:
            HUDTool.show(message: "该医生图文问诊暂无排班")
        }
    }
    
    private func reserveCloud() {
        guard let vm = viewModel else { return }
        
        switch vm.doctorType {
        case .cloud, .all:
            if vm.scheduleList.isEmpty {
                HUDTool.show(message: "该医生云门诊暂无排班")
            } else {
                let newCloudVc = NewCloudReserveController(with: vm)
                navigationController?.pushViewController(newCloudVc, animated: true)
            }
        default:
            HUDTool.show(message: "该医生云门诊暂无排班")
        }
    }
    
    func getTextHeigh(textStr :  String, font : UIFont, width : CGFloat)  -> CGFloat{
        let normalText : NSString = textStr as NSString
        let size = CGSize(width: width, height:1000) //CGSizeMake(width,1000)
        let dic = NSDictionary(object: font, forKey : kCTFontAttributeName as! NSCopying)
        let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key:Any], context:nil).size
        return stringSize.height
    }
}
